package com.wchen.game.server.handle;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Author: wchen
 * @Description:
 * @Date: Created in 2019-04-24 14:46
 * Copyright 本内容仅限于杭州阿拉丁信息科技股份有限公司内部传阅，禁止外泄以及用于其他的商业目的
 */
public class LoginHandle extends ChannelInboundHandlerAdapter {
    private final static Logger LOGGER = LoggerFactory.getLogger(LoginHandle.class);
    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        LOGGER.info("LoginHandle 注册事件 ...");
        super.channelRegistered(ctx);
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        LOGGER.info("LoginHandle 取消注册事件 ...");
        super.channelUnregistered(ctx);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        LOGGER.info("LoginHandle 客户端接入 ...");
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        LOGGER.info("LoginHandle 客户端断开...");
        super.channelInactive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        LOGGER.info("LoginHandle 开始读取数据 ...");
        ByteBuf byteBuf = (ByteBuf) msg;
        byte[] readBytes = new byte[byteBuf.readableBytes()];
        byteBuf.markReaderIndex();
        byteBuf.readBytes(readBytes);
        LOGGER.info("服务端接收的请求数据：" + new String(readBytes));

        String response = "快下班了...";
        LOGGER.info("服务端响应数据：" + response);
        ctx.writeAndFlush(Unpooled.copiedBuffer(response.getBytes()));
        byteBuf.resetReaderIndex();
        super.channelRead(ctx, msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        LOGGER.info("LoginHandle 数据读取完成 ...");
        super.channelReadComplete(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        LOGGER.info("LoginHandle 出现异常 ...");
        super.exceptionCaught(ctx, cause);
    }
}
